const Koa = require('koa')
const Router = require('koa-router')
const { koaBody } = require('koa-body')
const bodyParser = require('koa-bodyparser')
//引入模块化的子路由
const {roleRouter} = require('./role')
const {accountsRouter} = require('./account')
const serve =  require('koa-static')
const fs = require('fs')
const path = require('path')

const app = new Koa()
const router = new Router()
const port = 3001

//密钥
app.keys = ['this is wuhan', 'fristDay']

/*加载koa-body中间件，使得请求体中的数据可以被正确解析同时被配置到ctx.request.body中，
在后续的路由中可以通过ctx.request.body获取body参数。*/
app.use(koaBody())
// 绑定静态资源
app.use(serve(path.join(__dirname, "../../client/build")));
app.use(bodyParser())
//绑定路由
router.use('/api', roleRouter)
router.use('/api', accountsRouter)

router.get("/api/md/:filename", getMarkDownFile)

// 所有路径都返回 index.html 文件
router.get('/userlist', getIndex);
router.get('/rolemanage', getIndex);
router.get('/', getIndex);
router.get('/userdetail', getIndex);
async function getIndex(ctx, next){
  console.log("收到请求了");
  const indexPath = path.join(__dirname, '../../client/build', 'index.html');
  ctx.type = 'html';
  ctx.body = fs.createReadStream(indexPath);
  await next()
}

async function getMarkDownFile(ctx, next){
    console.log("收到请求了");
    const filename = ctx.params.filename
    const markdownFilePath = path.join(__dirname, `../../client/src/pages/learnexp/md/${filename}`).toString()
    try {
        const content = await fs.promises.readFile(markdownFilePath, 'utf-8');
        ctx.body = {
            data:{content: content},
            msg:"得到markdown文件的内容"
        }
      } catch (error) {
        ctx.status = 400
        ctx.body = { msg: `文件找不到了${markdownFilePath}` }
        console.error('Failed to read Markdown file:', error);
      }
    await next()
}

app.use(router.routes()).use(router.allowedMethods())

app.listen(port);

console.log(`服务器已启动,当前监听端口为${port},ip为127.0.0.1`);